//package com.tiancheng.trade.payment.task.ums;
//
//import com.tiancheng.trade.commom.data.Result;
//import com.tiancheng.trade.commom.exception.BusinessException;
//import com.tiancheng.trade.commom.exception.error.BusinessErrorInfoEnum;
//import com.tiancheng.trade.commom.utils.ServiceLocator;
//import com.tiancheng.trade.payment.channel.bo.PaymentFlowDetailBO;
//import com.tiancheng.trade.payment.channel.bo.RefundCouponSettleBO;
//import com.tiancheng.trade.payment.configuration.UmsAllConfigs;
//import com.tiancheng.trade.payment.enums.CouponSettleBusinessTypeEnum;
//import com.tiancheng.trade.commom.core.enums.PaymentChannelEnum;
//import com.tiancheng.trade.commom.core.enums.SettleStatusEnum;
//import com.tiancheng.trade.payment.feign.FileUpload;
//import com.tiancheng.trade.payment.feign.MerchantService;
//import com.tiancheng.trade.commom.web.model.request.MerchantChannelRequestDTO;
//import com.tiancheng.trade.commom.web.model.response.MerchantChannelResponseDTO;
//import com.tiancheng.trade.payment.model.*;
//import com.tiancheng.trade.payment.service.*;
//import com.tiancheng.trade.payment.task.ums.bo.CouponSettleFileBo;
//import com.tiancheng.trade.payment.task.ums.bo.DownloadFileBo;
//import com.tiancheng.trade.payment.task.ums.bo.FileRetBo;
//import com.tiancheng.trade.payment.util.*;
//import com.xxl.job.core.biz.model.ReturnT;
//import com.xxl.job.core.handler.annotation.XxlJob;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang3.StringUtils;
//import org.redisson.api.RAtomicLong;
//import org.redisson.api.RLock;
//import org.redisson.api.RedissonClient;
//import org.springframework.stereotype.Component;
//import org.springframework.transaction.annotation.Transactional;
//import org.springframework.util.CollectionUtils;
//
//import javax.annotation.Resource;
//import java.io.File;
//import java.time.LocalDate;
//import java.time.LocalDateTime;
//import java.time.format.DateTimeFormatter;
//import java.util.*;
//import java.util.concurrent.TimeUnit;
//import java.util.stream.Collectors;
//
//import static com.tiancheng.trade.payment.util.CommonUtil.splitMap;
//
///**
// * @Author: likailun
// * @Description: 优惠券清分任务
// * @Date: create in 2021/12/16 10:02 上午
// */
//@Component
//@Slf4j
//public class UmsCouponSettleTask {
//
//    /**
//     * 单个文件明细数不超过5万条
//     */
//    private static final int FILE_MAX = 50000;
//    private static final String INTERFACE_PRE = "09";// 代付接口前缀
//    public static final String SETTLE_TIME_BEGIN = "00:00:00";
//    public static final String SETTLE_TIME_END = "23:59:59";
//    public static final String SETTLE_BACK_TIME = "23:30:00";
//    private static final String SETTLE_ERROR = "ERROR";
//    private static final String SETTLE_ING = "ING";
//    private static final String SETTLE_SUCCESS = "SUCCESS";
//    @Resource
//    private UmsAllConfigs umsAllConfigs;
//    @Resource
//    private RedissonClient redissonClient;
//    @Resource
//    private PaymentFlowDetailService flowDetailService;
//    @Resource
//    private MerchantService merchantService;
//    @Resource
//    private PaymentRefundService refundService;
//    @Resource
//    private PaymentRefundFlowDetailService refundFlowDetailService;
//    @Resource
//    private CouponSettlePayService couponSettlePayService;
//    @Resource
//    private CouponSettleRefundService couponSettleRefundService;
//    @Resource
//    private CouponSettleDetailService couponSettleDetailService;
//    @Resource
//    private CouponSettleFileService couponSettleFileService;
//    @Resource
//    private FileUpload fileUpload;
//
//    /**
//     * 银联优惠券资分自动任务
//     * 以商户为维度聚合指令，一个商户一条指令
//     * 只上传（并记录到数据库）可以正常清分的订单，非正常订单滞留并记录
//     *
//     * @param param {@link String}
//     * @return {@link ReturnT <String>}
//     */
//    @Transactional
//    @XxlJob("doUmsCouponSettle")
//    public ReturnT<String> doUmsCouponSettle(String param) {
//        // 同时刻不允许有多个任务处理相同数据
//        RLock lock = redissonClient.getLock("UMS_COUPON_UPLOAD_SETTLE");
//        final LocalDateTime expectSettleTimeBegin = DateTimeUtil.string2LocalDateTime(DateTimeUtil.temporalFormat2String(LocalDateTime.now().minusDays(1), "yyyy-MM-dd") + " " + SETTLE_TIME_BEGIN, "yyyy-MM-dd HH:mm:ss");
//        final LocalDateTime expectSettleTimeEnd = DateTimeUtil.string2LocalDateTime(DateTimeUtil.temporalFormat2String(LocalDateTime.now().minusDays(1), "yyyy-MM-dd") + " " + SETTLE_TIME_END, "yyyy-MM-dd HH:mm:ss");
//        log.info("自动清分任务开始执行：{}-{}", expectSettleTimeBegin.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), expectSettleTimeEnd.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
//        long startTime = System.currentTimeMillis();
//        boolean isLock;
//        try {
//            isLock = lock.tryLock(30L, TimeUnit.MINUTES);
//            if (!isLock) {
//                log.error("自动清分任务执行结果：锁失败！");
//                return ReturnT.SUCCESS;
//            }
//
//            // 1、------------------------------------------------------------------------支付优惠处理
//            final Map<String, CouponSettleDetail> couponSettleDetailMap = new HashMap<>();// 清分明细行，merchant——商户清分明细
//            List<CouponSettlePay> settleMatches = new ArrayList<>(1000); // 可正常清分指令-流水明细映射记录
//            long startId = 0;
//            List<PaymentFlowDetailBO> list = null;
//            List<Long> lmList = new ArrayList<>(100); // 不可正常清分指令明细记录：缺少商户信息
//            Map<String, List<Long>> merchantFlowDetailIds = new HashMap<>(1000); // 记录每个商户可正常清分的支付子流水id
//            do {
//                list = flowDetailService.queryCouponSettlePayFlowDetail(expectSettleTimeBegin, expectSettleTimeEnd, startId);
//                if (CollectionUtils.isEmpty(list)) {
//                    continue;
//                }
//                Map<String, MerchantChannelResponseDTO> merchantMap = new HashMap<>();
//                // 1.2、查询商户的企业用户信息
//                Result<List<MerchantChannelResponseDTO>> merRepResult = merchantService.listByMerchantCodeAndChannel(
//                        list.stream().map(PaymentFlowDetail::getMerchantCode).collect(Collectors.toSet())
//                                .stream().map(merchantCode -> new MerchantChannelRequestDTO(merchantCode, PaymentChannelEnum.UMS.getCode())).collect(Collectors.toList())
//                );
//                if (merRepResult.getData().size() < 1) {
//                    log.error("优惠券清分任务执行结果：缺少渠道商户信息！");
//                    // 更新下标到当前list的最后一条记录
//                    startId = list.get(list.size() - 1).getId();
//                    // 设置流水缺失商户清分信息
//                    list.forEach(bo -> lmList.add(bo.getId()));
//                    continue;
//                }
//                for (MerchantChannelResponseDTO datum : merRepResult.getData()) {
//                    if (StringUtils.isEmpty(datum.getEnterpriseCode())) {
//                        log.warn("优惠券清分，商户企业用户号缺失，商户号:{}", datum.getMerchantCode());
//                        continue;
//                    }
//                    merchantMap.put(datum.getMerchantCode(), datum);
//                    if (StringUtils.isNotEmpty(datum.getMerchantCodeBusiness())) {
//                        merchantMap.put(datum.getMerchantCodeBusiness(), datum);
//                    }
//                }
//                for (PaymentFlowDetailBO bo : list) {
//                    startId = bo.getId();
//                    // 1.3、判断对应商户信息
//                    if (null == merchantMap.get(bo.getMerchantCode()) || StringUtils.isEmpty(merchantMap.get(bo.getMerchantCode()).getEnterpriseCode())) {
//                        lmList.add(bo.getId());
//                        log.warn("优惠券清分，商户企业用户号缺失，商户号:{}", bo.getMerchantCode());
//                        continue;
//                    }
//                    // 1.4、可正常清分处理逻辑
//                    if (merchantFlowDetailIds.get(bo.getMerchantCode()) == null) {
//                        merchantFlowDetailIds.put(bo.getMerchantCode(), new ArrayList<Long>() {{
//                            add(bo.getId());
//                        }});
//                    } else {
//                        merchantFlowDetailIds.get(bo.getMerchantCode()).add(bo.getId());
//                    }
//
//                    if (null == couponSettleDetailMap.get(bo.getMerchantCode())) {
//                        // 划付内容
//                        CouponSettleDetail settleDetail = new CouponSettleDetail();
//                        settleDetail.setSettleId(this.settleIdHelper(INTERFACE_PRE, CouponSettleBusinessTypeEnum.TRANSFER_OUT));
//                        settleDetail.setMerchantCode(bo.getMerchantCode());
//                        settleDetail.setBusinessType(CouponSettleBusinessTypeEnum.TRANSFER_OUT.getCode());// 默认转出，需要在统计退款时候矫正
//                        settleDetail.setEnterpriseCode(merchantMap.get(bo.getMerchantCode()).getEnterpriseCode());
//                        settleDetail.setPayCouponAmount(bo.getPlatformDiscount());// 支付订单优惠金额
//                        settleDetail.setRefundCouponAmount(0);
//                        settleDetail.setSettleStatus(SettleStatusEnum.ING.getCode()); // 结算状态：ING=结算中；SUCCESS=结算成功；FAIL=结算失败
//                        settleDetail.setSettleRemarks("腾云" + bo.getFlowCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + "优惠券清算");
//                        settleDetail.setServiceAmount(0);// 手续费，默认0，回盘时再修改
//                        settleDetail.setCreateTime(LocalDateTime.now());
//                        settleDetail.setUpdateTime(LocalDateTime.now());
//                        couponSettleDetailMap.put(bo.getMerchantCode(), settleDetail); // 收集指令
//                    } else {
//                        couponSettleDetailMap.get(bo.getMerchantCode()).setPayCouponAmount(couponSettleDetailMap.get(bo.getMerchantCode()).getPayCouponAmount() + bo.getPlatformDiscount());
//                    }
//                    // 3.4 生成支付优惠订单明细记录
//                    settleMatches.add(new CouponSettlePay(couponSettleDetailMap.get(bo.getMerchantCode()).getSettleId(), bo.getSubOrderId(), bo.getSubOrderFlowId()));
//                }
//                // 3.5 保存支付优惠订单明细记录
//                if (!CollectionUtils.isEmpty(settleMatches)) {
//                    couponSettlePayService.saveBatch(settleMatches);
//                }
//                // 3.6 更新“缺少商户信息或商户企业用户号”
//                if (!CollectionUtils.isEmpty(lmList)) {
//                    flowDetailService.updateSettleBatch(lmList, new HashMap<String, Object>() {{
//                        put("coupon_settle_status", SETTLE_ERROR);
//                    }});
//                }
//                settleMatches.clear();
//                lmList.clear();
//            } while (list.size() > 999);
//            log.info("优惠券清分，获取支付优惠完成");
//
//            // 4、------------------------------------------------------------------------退款优惠处理
//            Map<String, List<Long>> refundDetails = this.handleRefundCoupon(expectSettleTimeEnd, merchantFlowDetailIds, couponSettleDetailMap);
//            log.info("优惠券清分，获取退款优惠完成");
//            // 5、------------------------------------------------------------------------钆差处理
//            if (couponSettleDetailMap.isEmpty()) {
//                log.info("优惠券清分，当日无可清分优惠");
//                return ReturnT.SUCCESS;
//            }
//            List<Long> settleIngPay = new ArrayList<>();
//            List<Long> settleIngRefund = new ArrayList<>();
//
//            List<Long> settleErrorPay = new ArrayList<>();
//            List<Long> settleErrorRefund = new ArrayList<>();
//            for (Map.Entry<String, CouponSettleDetail> item : couponSettleDetailMap.entrySet()) {
//                if (!CollectionUtils.isEmpty(refundDetails.get(item.getKey()))) {
//                    // 该商户当天————有退款优惠待清分
//                    if (item.getValue().getPayCouponAmount() > item.getValue().getRefundCouponAmount()) {
//                        // 支付>退款————资金转出：营销户->商户
//                        item.getValue().setSettleCouponAmount(item.getValue().getPayCouponAmount() - item.getValue().getRefundCouponAmount());
//                        item.getValue().setBusinessType(CouponSettleBusinessTypeEnum.TRANSFER_OUT.getCode());
//                        item.getValue().setAllowReturnAmount(item.getValue().getSettleCouponAmount());
//
//                        // 支付流水、退款流水都设置清分状态为：ING
//                        if (!CollectionUtils.isEmpty(merchantFlowDetailIds.get(item.getKey()))) {
//                            settleIngPay.addAll(merchantFlowDetailIds.get(item.getKey()));
//                        }
//                        if (!CollectionUtils.isEmpty(refundDetails.get(item.getKey()))) {
//                            settleIngRefund.addAll(refundDetails.get(item.getKey()));
//                        }
//                        log.info("优惠券清分，资金转出营销户，商户：{}", item.getKey());
//                    } else if (item.getValue().getPayCouponAmount() < item.getValue().getRefundCouponAmount()) {
//                        // 支付<退款————记录支付流水&退款流水&优惠清分明细标识失败，优惠清分汇总记录失败
//                        item.getValue().setSettleCouponAmount(item.getValue().getRefundCouponAmount() - item.getValue().getPayCouponAmount());
//                        item.getValue().setBusinessType(CouponSettleBusinessTypeEnum.TRANSFER_IN.getCode());
//                        item.getValue().setAllowReturnAmount(0);// 资金转入时，不允许再作为转款反交易的关联
//                        log.info("优惠券清分，资金转入营销户，商户：{}", item.getKey());
//
//                        //查询该商户以完成清分且金额足够关联该笔反交易的转款补贴记录
//                        CouponSettleDetail sourceSettles = couponSettleDetailService.getSourceSettles(item.getKey(), item.getValue().getSettleCouponAmount());
//                        if (null == sourceSettles) {
//                            log.info("优惠券清分，转款补贴反交易无满足可清分的转款，商户：{},金额:{}", item.getKey(), item.getValue().getSettleCouponAmount());
//                            // 支付流水、退款流水都设置清分状态为：ERROR
//                            item.getValue().setSettleRemarks("转款补贴反交易无可关联的的转款正交易");
//                            item.getValue().setSettleStatus(SettleStatusEnum.FAIL.getCode());
//                            if (!CollectionUtils.isEmpty(merchantFlowDetailIds.get(item.getKey()))) {
//                                settleErrorPay.addAll(merchantFlowDetailIds.get(item.getKey()));
//                            }
//                            if (!CollectionUtils.isEmpty(refundDetails.get(item.getKey()))) {
//                                settleErrorRefund.addAll(refundDetails.get(item.getKey()));
//                            }
//                            continue;
//                        }
//                        item.getValue().setSourceSettleId(sourceSettles.getSettleId());
//                        item.getValue().setSourceSettleAmount(sourceSettles.getSettleCouponAmount());
//                        // 修改原交易订单可退补贴金额
//                        couponSettleDetailService.updateAllowReturnAmount(sourceSettles.getSettleId(), item.getValue().getSettleCouponAmount());
//                        // 支付流水、退款流水都设置清分状态为：ING
//                        if (!CollectionUtils.isEmpty(merchantFlowDetailIds.get(item.getKey()))) {
//                            settleIngPay.addAll(merchantFlowDetailIds.get(item.getKey()));
//                        }
//                        if (!CollectionUtils.isEmpty(refundDetails.get(item.getKey()))) {
//                            settleIngRefund.addAll(refundDetails.get(item.getKey()));
//                        }
//                    } else {
//                        // 资金不变，该记录不需要发送给银联，交易中台记录即可，转出金额为0
//                        item.getValue().setSettleCouponAmount(item.getValue().getPayCouponAmount() - item.getValue().getRefundCouponAmount());
//                        item.getValue().setBusinessType(CouponSettleBusinessTypeEnum.TRANSFER_OUT.getCode());
//                        item.getValue().setAllowReturnAmount(item.getValue().getSettleCouponAmount());
//                        item.getValue().setSettleStatus(SettleStatusEnum.SUCCESS.getCode());
//                        // 支付流水、退款流水都设置清分状态为：SUCCESS
//                        if (!CollectionUtils.isEmpty(merchantFlowDetailIds.get(item.getKey()))) {
//                            flowDetailService.updateSettleBatch(merchantFlowDetailIds.get(item.getKey()), new HashMap<String, Object>() {{
//                                put("coupon_settle_status", SETTLE_SUCCESS);
//                            }});
//                        }
//                        if (!CollectionUtils.isEmpty(refundDetails.get(item.getKey()))) {
//                            refundFlowDetailService.updateSettleBatch(refundDetails.get(item.getKey()), new HashMap<String, Object>() {{
//                                put("coupon_settle_status", SETTLE_SUCCESS);
//                            }});
//                        }
//                        log.info("优惠券清分，资金钆差为0，商户：{}", item.getKey());
//                    }
//                } else {
//                    // 该商户当天————无退款优惠待清分
//                    item.getValue().setSettleCouponAmount(item.getValue().getPayCouponAmount() - item.getValue().getRefundCouponAmount());
//                    item.getValue().setBusinessType(CouponSettleBusinessTypeEnum.TRANSFER_OUT.getCode());
//                    item.getValue().setAllowReturnAmount(item.getValue().getSettleCouponAmount());
//                    // 支付流水、退款流水都设置清分状态为：ING
//                    if (!CollectionUtils.isEmpty(merchantFlowDetailIds.get(item.getKey()))) {
//                        settleIngPay.addAll(merchantFlowDetailIds.get(item.getKey()));
//                    }
//                    log.info("优惠券清分，资金转出营销户，商户：{}", item.getKey());
//                }
//            }
//
//            // 支付流水、退款流水都设置清分状态为：SUCCESS
//            if (!CollectionUtils.isEmpty(settleIngPay)) {
//                flowDetailService.updateSettleBatch(settleIngPay, new HashMap<String, Object>() {{
//                    put("coupon_settle_status", SETTLE_ING);
//                }});
//            }
//            if (!CollectionUtils.isEmpty(settleIngRefund)) {
//                refundFlowDetailService.updateSettleBatch(settleIngRefund, new HashMap<String, Object>() {{
//                    put("coupon_settle_status", SETTLE_ING);
//                }});
//            }
//
//            if (!CollectionUtils.isEmpty(settleErrorPay)) {
//                flowDetailService.updateSettleBatch(settleErrorPay, new HashMap<String, Object>() {{
//                    put("coupon_settle_status", SETTLE_ERROR);
//                }});
//            }
//            if (!CollectionUtils.isEmpty(settleErrorRefund)) {
//                refundFlowDetailService.updateSettleBatch(settleErrorRefund, new HashMap<String, Object>() {{
//                    put("coupon_settle_status", SETTLE_ERROR);
//                }});
//            }
//            log.info("优惠券清分，退款钆差完成");
//            // 6、------------------------------------------------------------------------保存优惠清分明细、优惠清分汇总
//            final List<File> settleFiles = new ArrayList<>();
//            this.generateSettleFileSaveSettleRecord(couponSettleDetailMap, settleFiles);
//            couponSettleDetailMap.clear();
//            log.info("优惠券清分，保存清分记录完成");
//            //BusinessErrorInfoEnum.UMS_SETTLE_ERROR.assertFail();
//            // 7、------------------------------------------------------------------------上传文件到银联sftp
//            log.info("当前系统环境：{}", ServiceLocator.getEnvironment());
//            String path = umsAllConfigs.getUmsSettleDirPre() + "/" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")); // 服务器文件目录
//            UmsFileHandler.parallelUploadFile(path, settleFiles, new ArrayList<>());
//            log.info("优惠券清分，上传文件至银联sftp完毕");
//            /*if (ServiceLocator.getEnvironment().equals("prod")) {
//                String path = umsProperties.getUmsSettleDirPre() + "/" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")); // 服务器文件目录
//                UmsFileHandler.parallelUploadFile(path, settleFiles, new ArrayList<>());
//                log.info("优惠券清分，上传文件至银联sftp完毕");
//            }*/
//        } catch (Exception e) {
//            log.error("优惠券清分，自动任务执行失败：", e);
//            throw new BusinessException(BusinessErrorInfoEnum.UMS_SETTLE_ERROR, null, "优惠券清分，自动任务执行失败", e);
//        } finally {
//            if (lock.isLocked()) {
//                lock.unlock();
//            }
//            log.info("优惠券清分完成，共耗时：{}s", (System.currentTimeMillis() - startTime) / 1000);
//        }
//        return ReturnT.SUCCESS;
//    }
//
//
//    /**
//     * 银联资管-优惠券回盘文件处理
//     * - 获取执行任务前一天到现在有改动的优惠券回盘文件
//     *
//     * @param param {@link String} 指定的某个时间起
//     * @return {@link ReturnT<String>}
//     */
//    @XxlJob("doUmsCouponSettleCounteroffer")
//    public ReturnT<String> doUmsCouponSettleCounteroffer(String param) {
//        // 1、文件改动时间基点: 时间固定到位当天凌晨5点到前一天凌晨5点
//        LocalDateTime startDate = DateTimeUtil.string2LocalDateTime(DateTimeUtil.temporalFormat2String(LocalDateTime.now(), "yyyy-MM-dd") + " " + SETTLE_BACK_TIME, "yyyy-MM-dd HH:mm:ss");
//        if (!StringUtils.isEmpty(param)) {
//            param += (" " + SETTLE_BACK_TIME);
//            startDate = DateTimeUtil.string2LocalDateTime(param, "yyyy-MM-dd HH:mm:ss");
//        }
//        log.info("优惠券清分，开始处理回盘划付文件，任务开始时间：{}", DateTimeUtil.temporalFormat2String(startDate, "yyyy-MM-dd HH:mm:ss"));
//        try {
//            // 2、下载目标文件到目标服务器目标目录，并返回文件名信息
//            List<DownloadFileBo> files = UmsFileHandler.downloadCouponFile(startDate, "/" + umsAllConfigs.getUmsSettleDirPre() + "/", fileUpload);
//            if (files.isEmpty()) {
//                return ReturnT.SUCCESS;
//            }
//            // 3、获取文件内容
//            List<FileRetBo> fileRetBos = UmsFileHandler.readRemoteFiles(files, INTERFACE_PRE + "_");
//            if (fileRetBos.isEmpty()) {
//                log.info("划付回盘文件处理，未获取到需要处理的文件!");
//                return ReturnT.SUCCESS;
//            }
//            Set<String> fileNames = fileRetBos.stream().map(fileRetBo -> getSourceFileName(fileRetBo.getFileName())).collect(Collectors.toSet());
//            List<CouponSettleFile> couponSettleFiles = couponSettleFileService.queryByFileNames(fileNames);
//            BusinessErrorInfoEnum.ASSET_MANAGEMENT_NOT_FOUNT_APPROPRIATIONS_FILE.assertIsTrue(!CollectionUtils.isEmpty(couponSettleFiles));
//            List<CouponSettleFileBo> settleFileBos = new ArrayList<>();
//            // 4、开始对文件处理
//            for (FileRetBo fileRetBo : fileRetBos) {
//                // 汇总行
//                List<Object[]> summaryRowData = fileRetBo.getRowData(0, 1);
//                if (CollectionUtils.isEmpty(summaryRowData) || null == summaryRowData.get(0)) {
//                    log.error("文件没有内容，汇总行为空，文件名称：{}", fileRetBo.getFileName());
//                    //没有汇总信息
//                    continue;
//                }
//                // 解析数据
//                List<CouponSettleFile> collect = new ArrayList<>();
//                String fileName = fileRetBo.getFileName().replace(".ret", "");
//                for (CouponSettleFile settleFile : couponSettleFiles) {
//                    if (StringUtils.isNotBlank(settleFile.getFileName()) && settleFile.getFileName().equals(fileName)) {
//                        collect.add(settleFile);
//                    }
//
//                }
//                if (CollectionUtils.isEmpty(collect)) {
//                    log.error("未查询到优惠清分文件，文件名称：{}", fileName);
//                    continue;
//                }
//
//                // 文件明细处理
//                List<Object[]> detailRowData = fileRetBo.getRowData(1, fileRetBo.getData().length);
//                if (CollectionUtils.isEmpty(detailRowData)) {
//                    log.error("文件没有内容，明细行为空，文件名称：{}", fileRetBo.getFileName());
//                    //settleFileService.updateNoneSettle(getSettleFileBo(fileRetBo, summaryRowData, collect));
//                    //没有详细信息
//                } else {
//                    CouponSettleFileBo settleFileBo = getSettleFileBo(fileRetBo, summaryRowData, collect);
//                    settleFileBos.add(settleFileBo);
//                }
//
//            }
//            log.info("更新划付回盘文件解析结果：{}", JsonUtil.toJsonString(settleFileBos));
//            // 5、保存划付文件结果
//            if (!CollectionUtils.isEmpty(settleFileBos)) {
//                couponSettleFileService.saveCouponSettleResult(settleFileBos);
//            }
//        } catch (Exception e) {
//            log.error("划付回盘文件处理异常", e);
//            return ReturnT.FAIL;
//        }
//
//        return ReturnT.SUCCESS;
//    }
//
//
//    /**
//     * 解析回盘文件结果
//     *
//     * @param fileRetBo
//     * @param summaryRowData
//     * @param collect
//     * @return
//     */
//    private CouponSettleFileBo getSettleFileBo(FileRetBo fileRetBo, List<Object[]> summaryRowData, List<CouponSettleFile> collect) {
//        String sourceFileName = getSourceFileName(fileRetBo.getFileName());
//        CouponSettleFileBo settleFileBo = new CouponSettleFileBo();
//        settleFileBo.setId(collect.get(0).getId());
//        settleFileBo.setFileName(sourceFileName);
//        settleFileBo.setCheckSuccess(true);
//        settleFileBo.setUpdateDate(new Date());
//        settleFileBo.setTransferOutScNum(0);
//        settleFileBo.setTransferOutScAmount(0);
//        settleFileBo.setTransferOutErNum(0);
//        settleFileBo.setTransferOutErAmount(0);
//        settleFileBo.setTransferInScNum(0);
//        settleFileBo.setTransferInScAmount(0);
//        settleFileBo.setTransferInErNum(0);
//        settleFileBo.setTransferOutErAmount(0);
//        // TODO 解析回盘结果
//        if (sourceFileName.startsWith(INTERFACE_PRE + "_")) {
//            // 汇总行,状态校验
//            if (summaryRowData.get(0)[1].equals("2")) {
//                settleFileBo.setCheckSuccess(false);
//                return settleFileBo;
//            }
//            // 有明细行
//            List<Object[]> sourceDetailData = fileRetBo.getRowData(1, fileRetBo.getData().length);
//            if (!CollectionUtils.isEmpty(sourceDetailData)) {
//                List<CouponSettleDetail> couponSettleDetails = couponSettleDetailService.queryByFileName(sourceFileName);
//                List<CouponSettleDetail> couponSettleDetailList = new ArrayList<>(sourceDetailData.size());
//                for (Object[] sourceDetailDatum : sourceDetailData) {
//                    String settleId = sourceDetailDatum[0].toString();
//                    Optional<CouponSettleDetail> settleDetailOptional = couponSettleDetails.stream().filter(couponSettleDetail -> couponSettleDetail.getSettleId().equals(settleId)).findFirst();
//                    if (!settleDetailOptional.isPresent()) {
//                        log.error("优惠券清分回盘，未知的清分记录明细:{}", JsonUtil.toJsonString(sourceDetailDatum));
//                        continue;
//                    }
//                    CouponSettleDetail settleDetail = settleDetailOptional.get();
//                    settleDetail.setSettleStatus(this.getSettleStatus(sourceDetailDatum[5].toString()).getCode());
//                    if (settleDetail.getSettleStatus().equals(SettleStatusEnum.ING.getCode())) {
//                        log.info("优惠券清分回盘，回盘状态为ING或未知状态，不处理。settleId:{}", settleDetail.getSettleId());
//                        continue;
//                    }
//                    if (null != sourceDetailDatum[4] && Integer.parseInt(sourceDetailDatum[4].toString()) > 0) {
//                        if (!settleDetail.getSettleCouponAmount().equals(Integer.parseInt(sourceDetailDatum[4].toString()))) {
//                            log.info("优惠券清分回盘，回盘金额于原金额不一致，原金额：{},回盘金额：{}", settleDetail.getSettleCouponAmount(), sourceDetailDatum[4].toString());
//                            settleDetail.setSettleCouponAmount(Integer.parseInt(sourceDetailDatum[4].toString()));
//                        }
//                    }
//                    if (sourceDetailDatum[6] != null && !StringUtils.isEmpty(sourceDetailDatum[6].toString())) {
//                        settleDetail.setSettleRemarks(sourceDetailDatum[6].toString());
//                    }
//                    settleDetail.setOutSettleCode(sourceDetailDatum[7].toString());
//                    settleDetail.setServiceAmount(Integer.valueOf(sourceDetailDatum[8].toString()));// 手续费
//                    settleDetail.setUpdateTime(LocalDateTime.now());
//                    couponSettleDetailList.add(settleDetail);
//                }
//
//                // 计算汇总信息
//                if (!CollectionUtils.isEmpty(couponSettleDetailList)) {
//                    couponSettleDetailList.stream().collect(Collectors.groupingBy(CouponSettleDetail::getBusinessType)).forEach((cfd, list) -> {
//                        if (!CollectionUtils.isEmpty(list)) {
//                            Map<String, List<CouponSettleDetail>> collect1 = list.stream().collect(Collectors.groupingBy(CouponSettleDetail::getSettleStatus));
//                            if (!collect1.isEmpty()) {
//                                if (cfd.equals(CouponSettleBusinessTypeEnum.TRANSFER_OUT.getCode())) {
//                                    // 转出
//                                    if (collect1.containsKey(SettleStatusEnum.SUCCESS.getCode()) && !CollectionUtils.isEmpty(collect1.get(SettleStatusEnum.SUCCESS.getCode()))) {
//                                        settleFileBo.setTransferOutScNum(collect1.get(SettleStatusEnum.SUCCESS.getCode()).size());
//                                        settleFileBo.setTransferOutScAmount(collect1.get(SettleStatusEnum.SUCCESS.getCode()).stream().mapToInt(CouponSettleDetail::getSettleCouponAmount).sum());
//                                    }
//                                    if (collect1.containsKey(SettleStatusEnum.FAIL.getCode()) && !CollectionUtils.isEmpty(collect1.get(SettleStatusEnum.FAIL.getCode()))) {
//                                        settleFileBo.setTransferOutErNum(collect1.get(SettleStatusEnum.FAIL.getCode()).size());
//                                        settleFileBo.setTransferOutErAmount(collect1.get(SettleStatusEnum.FAIL.getCode()).stream().mapToInt(CouponSettleDetail::getSettleCouponAmount).sum());
//                                    }
//                                } else if (cfd.equals(CouponSettleBusinessTypeEnum.TRANSFER_IN.getCode())) {
//                                    // 转入
//                                    if (collect1.containsKey(SettleStatusEnum.SUCCESS.getCode()) && !CollectionUtils.isEmpty(collect1.get(SettleStatusEnum.SUCCESS.getCode()))) {
//                                        settleFileBo.setTransferInScNum(collect1.get(SettleStatusEnum.SUCCESS.getCode()).size());
//                                        settleFileBo.setTransferInScAmount(collect1.get(SettleStatusEnum.SUCCESS.getCode()).stream().mapToInt(CouponSettleDetail::getSettleCouponAmount).sum());
//                                    }
//                                    if (collect1.containsKey(SettleStatusEnum.FAIL.getCode()) && !CollectionUtils.isEmpty(collect1.get(SettleStatusEnum.FAIL.getCode()))) {
//                                        settleFileBo.setTransferInErNum(collect1.get(SettleStatusEnum.FAIL.getCode()).size());
//                                        settleFileBo.setTransferInErAmount(collect1.get(SettleStatusEnum.FAIL.getCode()).stream().mapToInt(CouponSettleDetail::getSettleCouponAmount).sum());
//                                    }
//                                }
//                            }
//                        }
//                    });
//                    settleFileBo.setSettleDetails(couponSettleDetailList);
//                }
//            }
//        }
//        return settleFileBo;
//    }
//
//    /**
//     * 银联清分状态
//     *
//     * @param umsStatus 清分状态
//     * @return
//     */
//    private SettleStatusEnum getSettleStatus(String umsStatus) {
//        if (StringUtils.isEmpty(umsStatus)) {
//            return SettleStatusEnum.ING;
//        }
//        switch (umsStatus) {
//            case "1":
//                return SettleStatusEnum.SUCCESS;
//            case "0":
//                return SettleStatusEnum.FAIL;
//            case "3":
//                log.warn("有优惠清分状态异常，需人工核实");
//                return SettleStatusEnum.ING;
//            default:
//                log.warn("未知的优惠清分状态：{}", umsStatus);
//                return SettleStatusEnum.ING;
//        }
//
//    }
//
//    /**
//     * 获取源文件名称
//     *
//     * @param fileName {@link String}
//     * @return {@link String}
//     */
//    private String getSourceFileName(String fileName) {
//        return fileName.replace(".ret", "");
//    }
//
//    /**
//     * @param expectSettleTimeEnd   清分时间
//     * @param merchantFlowDetailIds 当天需要做清分的支付流水记录id：flow_detail.id
//     * @param couponSettleDetailMap 支付优惠清分明细
//     * @return 当天参与优惠清分的退款明细id
//     */
//    private Map<String, List<Long>> handleRefundCoupon(LocalDateTime expectSettleTimeEnd, Map<String, List<Long>> merchantFlowDetailIds, Map<String, CouponSettleDetail> couponSettleDetailMap) {
//        Map<String, List<Long>> refundDetails = new HashMap<String, List<Long>>();
//        List<CouponSettleRefund> couponSettleRefund = new ArrayList<>();// 执行清分的退款流水关系
//        // 4.1、查询所有退款成功+银联渠道+未清分/清分失败+有优惠的退款明细
//        final List<RefundCouponSettleBO> refundCouponSettleBOS = refundService.queryCouponSettleRefund(expectSettleTimeEnd);
//        if (CollectionUtils.isEmpty(refundCouponSettleBOS)) {
//            log.info("优惠券清分，当日无退款优惠清分");
//            List<Long> allFlowDetailIds = new ArrayList<>();
//            merchantFlowDetailIds.values().forEach(allFlowDetailIds::addAll);
//            List<List<Long>> allFlowDetailIdSplits = CommonUtil.splitList(allFlowDetailIds, 2000); // 每2000为一次查询数量
//            for (List<Long> flowDetailIds : allFlowDetailIdSplits) {
//                if (CollectionUtils.isEmpty(flowDetailIds)) {
//                    log.info("优惠券清分，当日无退款优惠清分，支付流水为空。");
//                    continue;
//                }
//                flowDetailService.updateSettleBatch(flowDetailIds, new HashMap<String, Object>() {{
//                    put("coupon_settle_status", SETTLE_ING);
//                }});
//            }
//            return refundDetails;
//        }
//        // 4.2 查询当天有优惠退款的商户
//        final Set<String> settle_refund_merchant = refundCouponSettleBOS.stream().map(RefundCouponSettleBO::getMerchantCode).collect(Collectors.toSet());
//        Result<List<MerchantChannelResponseDTO>> merRepResult = merchantService.listByMerchantCodeAndChannel(
//                settle_refund_merchant.stream().map(merchantCode -> new MerchantChannelRequestDTO(merchantCode, PaymentChannelEnum.UMS.getCode())).collect(Collectors.toList())
//        );
//        Map<String, MerchantChannelResponseDTO> merchantMap = new HashMap<>();
//        if (merRepResult.getRet() == 0 && merRepResult.getData().size() > 0) {
//            for (MerchantChannelResponseDTO datum : merRepResult.getData()) {
//                if (StringUtils.isEmpty(datum.getEnterpriseCode())) {
//                    log.warn("优惠券清分，商户企业用户号缺失，商户号:{}", datum.getMerchantCode());
//                    continue;
//                }
//                merchantMap.put(datum.getMerchantCode(), datum);
//                if (StringUtils.isNotEmpty(datum.getMerchantCodeBusiness())) {
//                    merchantMap.put(datum.getMerchantCodeBusiness(), datum);
//                }
//            }
//        }
//        Map<Long, Integer> merchantCodeLostMap = new HashMap<>(100); // 缺少清分规则退款流水明细id
//        for (RefundCouponSettleBO bo : refundCouponSettleBOS) {
//            if (null == merchantMap.get(bo.getMerchantCode())) {
//                // 没查询到商户企业用户号码
//                merchantCodeLostMap.put(bo.getId(), 1);
//                log.warn("优惠券清分，商户企业用户号缺失，商户号:{}", bo.getMerchantCode());
//                continue;
//            }
//            // 计算退款返还优惠金额
//            if (null == couponSettleDetailMap.get(bo.getMerchantCode())) {
//                // 没有支付优惠划付，这里
//                CouponSettleDetail settleDetail = new CouponSettleDetail();
//                settleDetail.setSettleId(this.settleIdHelper(INTERFACE_PRE, CouponSettleBusinessTypeEnum.TRANSFER_IN));
//                settleDetail.setMerchantCode(bo.getMerchantCode());
//                settleDetail.setBusinessType(CouponSettleBusinessTypeEnum.TRANSFER_IN.getCode());// 默认转出，需要在统计退款时候矫正
//                settleDetail.setEnterpriseCode(merchantMap.get(bo.getMerchantCode()).getEnterpriseCode());
//                settleDetail.setPayCouponAmount(0);// 支付订单优惠金额
//                settleDetail.setRefundCouponAmount(bo.getRefundPlatformDiscount());
//                settleDetail.setSettleStatus(SettleStatusEnum.ING.getCode()); // 结算状态：ING=结算中；SUCCESS=结算成功；FAIL=结算失败
//                settleDetail.setSettleRemarks("腾云" + expectSettleTimeEnd.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + "优惠券清算");
//                settleDetail.setServiceAmount(0);// 手续费，默认0，回盘时再修改
//                settleDetail.setCreateTime(LocalDateTime.now());
//                settleDetail.setUpdateTime(LocalDateTime.now());
//
//                couponSettleDetailMap.put(bo.getMerchantCode(), settleDetail); // 收集指令
//            } else {
//                couponSettleDetailMap.get(bo.getMerchantCode()).setRefundCouponAmount(couponSettleDetailMap.get(bo.getMerchantCode()).getRefundCouponAmount() + bo.getRefundPlatformDiscount());
//            }
//
//            // 保存需要做清分的商户退款订单id
//            if (null == refundDetails.get(bo.getMerchantCode())) {
//                refundDetails.put(bo.getMerchantCode(), new ArrayList<Long>() {{
//                    add(bo.getId());
//                }});
//            } else {
//                refundDetails.get(bo.getMerchantCode()).add(bo.getId());
//            }
//            couponSettleRefund.add(new CouponSettleRefund() {{
//                setSettleId(couponSettleDetailMap.get(bo.getMerchantCode()).getSettleId());
//                setSubOrderId(bo.getSubOrderId());
//                setSubRefundFlowId(bo.getSubFlowId());
//            }});
//        }
//        // 4.3 记录未查询到商户信息的退款明细
//        if (!merchantCodeLostMap.isEmpty()) {
//            refundFlowDetailService.updateSettleBatch(merchantCodeLostMap.keySet(), new HashMap<String, Object>() {{
//                put("coupon_settle_status", SETTLE_ERROR);
//            }});
//        }
//
//        // 4.3 保存退款流水优惠关联
//        if (!couponSettleRefund.isEmpty()) {
//            couponSettleRefundService.saveBatch(couponSettleRefund);
//        }
//        return refundDetails;
//    }
//
//    /**
//     * 保存优惠清分明细、优惠清分汇总</br>
//     * 生成清分文件</br>
//     *
//     * @param settleDetailMap 清分明细
//     * @param settleFiles     返回清分文件列表
//     */
//    private void generateSettleFileSaveSettleRecord(Map<String, CouponSettleDetail> settleDetailMap, List<File> settleFiles) {
//        String toDay = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
//        int position = 1;
//        for (Map<String, CouponSettleDetail> map : splitMap(settleDetailMap, FILE_MAX)) {
//            String settleFileName = INTERFACE_PRE + "_" + umsAllConfigs.getGroupCode() + "_" + toDay + "_" + String.format("%04d", new Random().nextInt(9999)) + position + ".txt";
//            List<String> settleLines = new ArrayList<>(); // 清分文件明细行
//            settleLines.add(""); // 首行先占位，给汇总行预留
//
//            for (CouponSettleDetail couponSettleDetail : map.values()) {
//                couponSettleDetail.setFileName(settleFileName);
//                if (couponSettleDetail.getBusinessType().equals(CouponSettleBusinessTypeEnum.TRANSFER_OUT.getCode()) && couponSettleDetail.getSettleCouponAmount() == 0) {
//                    couponSettleDetail.setSettleStatus(SettleStatusEnum.SUCCESS.getCode());
//                    couponSettleDetail.setSettleRemarks("清分优惠金额为钆差为0，不执行清分");
//                    log.info("优惠清分，清分优惠金额为钆差为0，不执行清分。商户：{}", couponSettleDetail.getMerchantCode());
//                    continue;
//                }
//                if (couponSettleDetail.getBusinessType().equals(CouponSettleBusinessTypeEnum.TRANSFER_IN.getCode()) && couponSettleDetail.getSettleStatus().equals(SettleStatusEnum.FAIL.getCode())) {
//                    // 转入的+状态是失败的，不发给银联
//                    log.warn("优惠清分，转入失败。商户：{}，原因：{}", couponSettleDetail.getMerchantCode(), couponSettleDetail.getSettleRemarks());
//                    continue;
//                }
//                if (couponSettleDetail.getSettleCouponAmount() != 0) {
//                    if (couponSettleDetail.getBusinessType().equals(CouponSettleBusinessTypeEnum.TRANSFER_OUT.getCode())) {
//                        settleLines.add(couponSettleDetail.getSettleId() + "|" + CouponSettleBusinessTypeEnum.TRANSFER_OUT.getCode() + "|" +
//                                umsAllConfigs.getMarketingAccount() + "|" + couponSettleDetail.getEnterpriseCode() + "|" +
//                                couponSettleDetail.getSettleCouponAmount() + "|" + String.format("腾云%s日优惠清分（转出）", toDay));
//                    } else {
//                        settleLines.add(couponSettleDetail.getSettleId() + "|" + CouponSettleBusinessTypeEnum.TRANSFER_IN.getCode() + "|" +
//                                couponSettleDetail.getEnterpriseCode() + "|" + umsAllConfigs.getMarketingAccount() + "|" +
//                                couponSettleDetail.getSettleCouponAmount() + "|" + String.format("腾云%s日优惠清分（转入）", toDay) + "|" +
//                                couponSettleDetail.getSourceSettleId() + "|" + couponSettleDetail.getSourceSettleAmount());
//                    }
//
//                } else {
//                    couponSettleDetail.setSettleStatus(SettleStatusEnum.SUCCESS.getCode());
//                    couponSettleDetail.setSettleRemarks("清分优惠金额为0，不执行清分");
//                }
//
//            }
//            // 划付汇总行：集团编号|总笔数
//            settleLines.set(0, umsAllConfigs.getGroupCode() + "|" + (settleLines.size() - 1));
//            settleFiles.add(TxtUtil.createTxtFile(settleFileName, settleLines, "utf-8"));
//
//
//            CouponSettleFile couponSettleFile = new CouponSettleFile();
//
//            couponSettleFile.setClearDate(LocalDate.now());
//            couponSettleFile.setGroupCode(umsAllConfigs.getGroupCode());
//            couponSettleFile.setChannel(PaymentChannelEnum.UMS.getCode());
//            couponSettleFile.setBusinessType(1);// 1-转款补贴
//            couponSettleFile.setFileName(settleFileName);
//            //  转入-总笔数
//            couponSettleFile.setTransferInNum((int) map.values().stream()
//                    .filter(item -> item.getBusinessType().equals(CouponSettleBusinessTypeEnum.TRANSFER_IN.getCode())).count());
//            //  转入-总金额
//            couponSettleFile.setTransferInAmount(map.values().stream()
//                    .filter(item -> item.getBusinessType().equals(CouponSettleBusinessTypeEnum.TRANSFER_IN.getCode()))
//                    .mapToInt(CouponSettleDetail::getSettleCouponAmount).sum());
//            // 转入-失败-笔数
//            couponSettleFile.setTransferInErNum((int) map.values().stream()
//                    .filter(item -> item.getBusinessType().equals(CouponSettleBusinessTypeEnum.TRANSFER_IN.getCode()) &&
//                            item.getSettleStatus().equals(SettleStatusEnum.FAIL.getCode())).count());
//            // 转入-失败-金额
//            couponSettleFile.setTransferInErAmount(map.values().stream()
//                    .filter(item -> item.getBusinessType().equals(CouponSettleBusinessTypeEnum.TRANSFER_IN.getCode()) &&
//                            item.getSettleStatus().equals(SettleStatusEnum.FAIL.getCode()))
//                    .mapToInt(CouponSettleDetail::getSettleCouponAmount).sum());
//
//
//            //  转入-总笔数
//            couponSettleFile.setTransferOutNum((int) map.values().stream()
//                    .filter(item -> item.getBusinessType().equals(CouponSettleBusinessTypeEnum.TRANSFER_OUT.getCode())).count());
//            //  转入-总金额
//            couponSettleFile.setTransferOutAmount(map.values().stream()
//                    .filter(item -> item.getBusinessType().equals(CouponSettleBusinessTypeEnum.TRANSFER_OUT.getCode()))
//                    .mapToInt(CouponSettleDetail::getSettleCouponAmount).sum());
//            // 转入-失败-笔数
//            couponSettleFile.setTransferOutErNum((int) map.values().stream()
//                    .filter(item -> item.getBusinessType().equals(CouponSettleBusinessTypeEnum.TRANSFER_OUT.getCode()) &&
//                            item.getSettleStatus().equals(SettleStatusEnum.FAIL.getCode())).count());
//            // 转入-失败-金额
//            couponSettleFile.setTransferOutErAmount(map.values().stream()
//                    .filter(item -> item.getBusinessType().equals(CouponSettleBusinessTypeEnum.TRANSFER_OUT.getCode()) &&
//                            item.getSettleStatus().equals(SettleStatusEnum.FAIL.getCode()))
//                    .mapToInt(CouponSettleDetail::getSettleCouponAmount).sum());
//
//            couponSettleFile.setTransferInScNum(couponSettleFile.getTransferInNum() - couponSettleFile.getTransferInErNum());
//            couponSettleFile.setTransferInScAmount(couponSettleFile.getTransferInAmount() - couponSettleFile.getTransferInErAmount());
//            couponSettleFile.setTransferOutScNum(couponSettleFile.getTransferOutNum() - couponSettleFile.getTransferOutErNum());
//            couponSettleFile.setTransferOutScAmount(couponSettleFile.getTransferOutAmount() - couponSettleFile.getTransferOutErAmount());
//            couponSettleFile.setServiceAmount(0);
//
//            couponSettleDetailService.saveBatch(new ArrayList<>(map.values()));
//            couponSettleFileService.save(couponSettleFile);
//            position++;
//        }
//    }
//
//    /**
//     * 指令id生成器，24位
//     *
//     * @param prefix {@link String} 前缀：09_=代付
//     * @return {@link String}
//     */
//    private String settleIdHelper(String prefix, CouponSettleBusinessTypeEnum typeEnum) {
//        String incrTime = DateTimeUtil.formatter(LocalDateTime.now(), "yyMMddHH");
//        String environment = ServiceLocator.getEnvironment().equalsIgnoreCase("prod") ? "P" : "T";
//        RAtomicLong rAtomicLong = redissonClient.getAtomicLong("paymentCouponSettle" + incrTime + environment);
//        long incr = rAtomicLong.incrementAndGet();
//        // 如果是当天第一个取号，就给key添加隔1小时失效时间
//        if (incr == 1) {
//            rAtomicLong.expireAsync(1, TimeUnit.HOURS);
//        }
//        return prefix + typeEnum.getCode() + environment + incrTime + String.format("%05d", incr);
//    }
//
//}
